//
//  AddDeviceViewModel.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/5/9.
//

import Foundation
import Combine
import ThingSmartDeviceKit
import ThingSmartActivatorDiscoveryManager
import SwiftUICore
import RealmSwift

struct Item: Identifiable{
    let id = UUID()
    let iconUrl: String
    let name: String
    let isOnline: Bool
    
    init(name: String, iconUrl: String, isOnline: Bool) {
        self.name = name
        self.iconUrl = iconUrl
        self.isOnline = isOnline
    }
}

class AddDeviceViewModel: ObservableObject {
    @Published var productList: [Level1Item] = []
    @Published var selectedProductList: [Level3Item] = []
    
    @Published var foundPeripherals: [Peripheral] = []
    @Published var selectedCategoryID: String?
    @Published var isSearching: Bool = false
    
    var founcPeripheralIds: [UUID] {
        let uuids = foundPeripherals.compactMap { $0.id }
        return uuids
    }
    let timeOutSeconds: Int32 = 180
    
    var cancellables = Set<AnyCancellable>()
    
    init()
    {
        self.foundPeripherals = CiotManager.shared.foundPeripherals
        CiotManager.shared.$foundPeripherals
            .receive(on: RunLoop.main)
            .sink { [weak self] peripherals in
                self?.foundPeripherals = peripherals
                guard let foundPeripherals = self?.foundPeripherals else {
                    return
                }
                for item in foundPeripherals {
                    if let level3Item = self?.getLevel3ItemBy(pid: item.pid) {
                        item.cover = level3Item.icon
                        item.name = level3Item.name
                    }
                }
                
            }
            .store(in: &cancellables)
        
        CiotManager.shared.$isSearching
            .receive(on: RunLoop.main)
            .sink { [weak self] isSearching in
                self?.isSearching = isSearching
            }
            .store(in: &cancellables)
        
        getCiotPrimaryCategory()
        startDiscovery()
    }
    

    
    private func getLevel3ItemBy(pid: String) -> Level3Item?
    {
        for model in productList {
            return model.level3List.first(where: { $0.pid == pid })
        }
        return nil
    }
    
    func getlist()
    {
        connectPeripheral(foundPeripherals[0])
        CiotManager.shared.$isConnectingCloud
            .receive(on: RunLoop.main)
            .sink { [weak self] peripherals in
                
                CiotProductManager.shared.getBindedList()
                    .sink(receiveCompletion: { completion in
                        switch completion {
                        case .finished:
                            break;
                        case .failure(let error):
                            print("失败: \(error)")
                        }
                    }, receiveValue: { model in
                        print("success \(model)")
                    })
                    .store(in: &self!.cancellables)
            }
            .store(in: &cancellables)
    }
    
    func connectPeripheral(_ selectedPeripheral: Peripheral?) {
    }
    
    deinit {
        CiotManager.shared.foundPeripherals.removeAll()
    }
    
    func startDiscovery()
    {
       let _ = CiotManager.shared.startDiscover(milliseconds: timeOutSeconds * 1000)
    }
    
    func stopDiscovery()
    {
        foundPeripherals = []
    }
    
    func getCiotPrimaryCategory()
    {
        CiotProductManager.shared.requireProductCategory()
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break;
                case .failure(let error):
                    print("获取ciot一级分类失败: \(error)")
                    self.getTuyaPrimaryCategory()
                }
            }, receiveValue: { [self] model in
                buildProductListData(categoryModel: model)
                self.getTuyaPrimaryCategory()
                print("获取产品ciot一级分类success \(model)")
            })
            .store(in: &cancellables)
    }
    
    func getTuyaPrimaryCategory()
    {
        TuyaManager.shared.requestPrimaryCategory()
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break;
                case .failure(let error):
                    print("获取一级分类失败: \(error)")
                }
            }, receiveValue: { [self] model in
                buildProductListData(categoryModel: model)
                self.selectedCategoryID = productList.first?.id
                getSecondaryCategory()
              
                print("获取产品一级分类success \(model)")
            })
            .store(in: &cancellables)
    }
    
    func getSecondaryCategory()
    {
        getCiotSecondaryCategory()
    }
    
    func getTuyaSecondaryCategory()
    {
        guard let index = self.productList.firstIndex(where: { $0.id == self.selectedCategoryID }) else {
           return
        }
        
        let selectCategory = self.productList[index]
        let code = selectCategory.code
        let type = selectCategory.type
        TuyaManager.shared.requestSecondaryCategory(level1code: code, type: type)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break;
                case .failure(let error):
                    print("获取一级分类失败: \(error)")
                }
            }, receiveValue: { [self] model in
                guard let model = model.first else{
                    return;
                }
                let level3List: List<Level3Item> = List<Level3Item>()
                model.level3Items.forEach{ item in
                    let level3Item = Level3Item()
                    level3Item.sale = item.sale
                    level3Item.capability = item.capability
                    level3Item.attribute = item.attribute
                    level3Item.name = item.name
                    level3Item.pid = item.pid
                    level3Item.icon = item.icon
                    level3Item.parentCode = selectCategory.code
                    level3Item.dataSource = "tuya"
                    level3List.append(level3Item)
                }
                DispatchQueue.main.async { [self] in
                    selectCategory.level3List.append(objectsIn: level3List)
                    selectedProductList.append(contentsOf: level3List)
                    self.productList[index].level3List = selectCategory.level3List
                }
                
                let str = self.productList.description
                print("获取产品一级分类success \(str)")
            })
            .store(in: &cancellables)
    }
    
    func getCiotSecondaryCategory()
    {
        guard let index = self.productList.firstIndex(where: { $0.id == self.selectedCategoryID }) else {
           return
        }
        
        let selectCategory = self.productList[index]
        let id = selectCategory.ciotId
        CiotProductManager.shared.requireProductsWithCategoryId(id)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break;
                case .failure(let error):
                    print("获取ciot 二级分类失败: \(error)")
                }
            }, receiveValue: { models in
               
                
                let level3List: List<Level3Item> = List<Level3Item>()
                models.forEach{ model in
                    let level3Item = Level3Item()
                    level3Item.name = model.name
                    level3Item.pid = model.pid
                    level3Item.icon = model.imgUrlStr
                    level3Item.applianceType = model.applianceType
                    level3Item.applianceTypeName = model.applianceTypeName
                    level3Item.model = model.model
                    level3Item.imgUrlStr = model.imgUrlStr
                    level3Item.devType = model.devType
                    level3Item.devTypeRemark = model.devTypeRemark
                    level3Item.otherConfig = model.otherConfig
                    level3Item.remark = model.remark
                    level3Item.status = model.status
                    level3Item.delFlag = model.delFlag
                    level3Item.createTime = model.createTime
                    level3Item.updateTime = model.updateTime
                    level3Item.parentCode = selectCategory.code
                    level3Item.dataSource = "ciot"
                    level3List.append(level3Item)
                }
                DispatchQueue.main.async {
                    selectCategory.level3List = level3List
                    self.productList[index].level3List = selectCategory.level3List
                    self.selectedProductList = level3List.map { $0 }
                    self.getTuyaSecondaryCategory()
                }
                
                print("获取产品ciot二级级分类success \(models)")
            })
            .store(in: &cancellables)
    }
    
    // 构建 产品类别数据
    func buildProductListData(categoryModel: ThingSmartACategoryModel)
    {
        categoryModel.level1List.forEach { (element) in
            
            let name = element.name
            let exists = productList.contains { product in
                if (product.name == name)
                {
                    product.code = element.level1Code
                    product.type = element.type
                    return true
                }
                return false
            }
            var level1List: [Level1Item] = []
            if exists == false {
                let level1Item = Level1Item()
                level1Item.name = element.name
                level1Item.code = element.level1Code
                level1Item.type = element.type
                level1List.append(level1Item)
            }else{
                
            }
            DispatchQueue.main.async {
                self.productList.append(contentsOf: level1List)
            }
        }
        
        if productList.count <= 0 { print("产品列表为空！"); return }
        
        categoryModel.defaultLevel2List.forEach{ (element_2) in
            var level3List: [Level3Item] = []
            element_2.level3Items.forEach{ (element_3) in
                let level3Item = Level3Item()
                level3Item.sale = element_3.sale
                level3Item.capability = element_3.capability
                level3Item.attribute = element_3.attribute
                level3Item.name = element_3.name
                level3Item.pid = element_3.pid
                level3Item.icon = element_3.icon
                level3Item.parentCode = categoryModel.level1List.first?.level1Code ?? ""
                level3Item.dataSource = "tuya"
                level3List.append(level3Item)
            }
            
            DispatchQueue.main.async {
                self.productList.first?.level3List.append(objectsIn: level3List)
            }
        }
    }
    
    // 构建 产品类别数据,ciot平台
    func buildProductListData(categoryModel: DeviceAPI.ApplianceTypeList.Response)
    {
        var level1List:[Level1Item] = [];
        categoryModel.forEach{ model in
                let level1Item = Level1Item()
                level1Item.name = model.name
                level1Item.ciotId = model.id
                level1Item.ciotNodeType = String(model.nodeType)
                level1Item.ciotCode = model.code
                level1Item.parentId = model.parentId
                level1Item.remark = model.remark ?? ""
                level1Item.deleted = model.deleted
                level1List.append(level1Item)
        }
        
        DispatchQueue.main.async {
            self.productList = level1List
        }
    }
}

class Level1Item: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var id: String // 涂鸦: 无, 凯度：无，主键唯一 ciotId_$_code：
    @Persisted var ciotId: String = "" {  // 涂鸦：无，凯度： id。       ciot请求二级列表时用
        didSet {
            updateId()
        }
    }
    @Persisted var code: String = "" {   // 涂鸦：level1Code，凯度： 无， 涂鸦请求二级列表时用
        didSet {
            updateId()
        }
    }
    @Persisted var ciotCode: String = ""        // 涂鸦：无，凯度： code
    @Persisted var name: String = ""
    @Persisted var type: String = ""        // 涂鸦：type， 凯度：无。   涂鸦请求二级列表时用
    @Persisted var ciotNodeType: String = "" // 涂鸦 无， 凯度: nodeType
    @Persisted var  parentId: String = ""   // 涂鸦：无， 凯度：parentId
    @Persisted var  remark: String = ""     // 涂鸦：无， 凯度：remark
    @Persisted var  deleted: String = ""   // 涂鸦：无， 凯度：deleted
    
    @Persisted var level3List: List<Level3Item> = List<Level3Item>()
    
    private func updateId() {
        let newId = "\(ciotId)_$_\(code)"
        if id != newId {
            id = newId
        }
    }
}


class Level3Item:  Object, ObjectKeyIdentifiable  {
    @Persisted(primaryKey: true) var pid: String  // 涂鸦：pid，凯度：pid
    @Persisted var sale: String = ""
    @Persisted var capability: Int64 = 0   // 涂鸦：capability，凯度：无
    @Persisted var attribute: String = ""   // 涂鸦：attribute，凯度：无
    @Persisted var name: String = ""        // 涂鸦：name，凯度：name
    @Persisted var icon: String = ""       // 涂鸦：icon， 凯度：imgUrlStr
    @Persisted var applianceType: String = ""  // 涂鸦：无， 凯度：applianceType，对应于上一级的 凯度code，也就是 ciotCode属性值
    @Persisted var applianceTypeName: String = "" // 涂鸦：无， 凯度：applianceTypeName，对应于上一级的 凯度name，也就是 name属性值
    @Persisted var model: String = ""
    @Persisted var imgUrlStr: String = ""
    @Persisted var devType: String = ""
    @Persisted var devTypeRemark: String = ""
    @Persisted var otherConfig: String = ""
    @Persisted var remark: String = ""
    @Persisted var status: String = ""
    @Persisted var delFlag: String = ""
    @Persisted var createTime: String = ""
    @Persisted var updateTime: String = ""
    @Published var  dataSource: String = "" // 值：ciot， tuya。代表数据来源
    @Persisted var parentCode:String = ""// 一级 id
}



//{"id":"1838816855362998274","applianceType":"020004","applianceTypeName":"集成水槽","pid":"uJOXYuLO","name":"凯度半自动咖啡机--菜谱","model":"NI2-MS2","imgUrl":"1838815571548143617","imgUrlStr":"https://minio.casdon.com.cn:30443/casdon/2024/09/25/bb65edf2b91c4bf8b744cbee75213078.jpg","devType":"wifi_ble","devTypeRemark":"C01","otherConfig":"sys_product_voice_interaction,sys_product_nfc,sys_product_camera","remark":"","status":"2","delFlag":"0","createTime":"2024-09-25 13:44:37","updateTime":"2025-03-10 15:48:28"}
